<template>
  <div>
    <!--    <van-nav-bar title="文件上传" @click-left="onCancel">-->
    <!--      <template #left>-->
    <!--        <i class="el-icon-arrow-left" style="font-size: 20px;" />-->
    <!--      </template>-->
    <!--    </van-nav-bar>-->

    <div class="file-upload">
      <input v-show="false" ref="upload" type="file" :accept="accept" @change="onFileChange">
      <div class="file-upload__title">文件上传</div>

      <div class="upload-container" @click="uploadFile">
        <div class="upload-container__icon">
          <i class="el-icon-upload icon" />
          <span>点击上传</span>
        </div>
      </div>

      <div class="progress-bar-container">
        <div class="progress">{{ progress }}</div>
        <div class="progress-bar">
          <div class="bar" :style="{ width: progress }" />
        </div>
      </div>

      <!--      <div class="file-upload__button">-->
      <!--        <button class="upload-btn">关闭</button>-->
      <!--      </div>-->

      <div class="file-upload__tips">
        文件上传格式为{{ accept }}，上传文件大小最大为<span style="color: red;">{{ MAX_SIZE }}MB</span>
      </div>
    </div>
  </div>
</template>
<script>
import 'vant/lib/index.css'
import { Toast, NavBar, Loading } from 'vant'
import axios from 'axios'
export default {
  name: '',
  components: {
    [Toast.name]: Toast,
    [NavBar.name]: NavBar,
    [Loading.name]: Loading
  },
  data() {
    return {
      accept: '.jpg, .jpeg, .png, .pdf, .doc, .docx',
      MAX_SIZE: 2,
      url: `${process.env.VUE_APP_UPLOAD}api/v1/upload/file`,
      progress: '0%',
      wx: null,
      uni: null,
      backUrl: ''
    }
  },
  created() {
    // this.createScriptElement()

    this.setScriptElement(this.wx, this.uni, this.filterDuplicate)
    console.log('this.$route --------->', this.$route)
    const { query: { accept, size, url }} = this.$route
    console.log('url --------->', url)
    if (accept) this.accept = accept
    if (size) this.MAX_SIZE = size / 1
    if (url) this.backUrl = url
  },
  methods: {

    setScriptElement(wx, uni, fun) {
      wx = document.createElement('script')
      uni = document.createElement('script')
      wx.id = 'wxScript'
      uni.id = 'uniScript'
      wx.type = 'text/javascript'
      uni.type = 'text/javascript'
      wx.async = false
      uni.async = false
      wx.src =
        'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/test_1659066827_VqED58Z4NF.js'
      uni.src =
        'https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/test_1659066855_4SntW8kOwj.js'
      fun('#wxScript') && fun('#wxScript').appendChild(wx)
      fun('#uniScript') && fun('#uniScript').appendChild(uni)
    },

    filterDuplicate(id) {
      if (document.head.querySelector(id)) {
        return null
      } else {
        return document.head
      }
    },

    onCancel() {
      uni.postMessage({
        data: {
          status: 'cancel'
        }
      })
    },

    onFileChange(e) {
      const file = e.target.files[0]
      if (file.size > this.MAX_SIZE * 1024 * 1024) {
        this.onExceed()
        return
      }
      this.uploading(file)
    },

    uploadFile() {
      this.$refs.upload.click()
    },

    onExceed() {
      Toast.fail({ message: `文件大小不超过${this.MAX_SIZE}MB` })
    },

    uploading(file) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('folder', 'test')
      this.uploadApi(formData)
    },
    async uploadApi(data) {
      const that = this
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        transformRequest: [function(data) {
          return data
        }],
        onUploadProgress(progressEvent) {
          const percent = (progressEvent.loaded / progressEvent.total * 100 | 0)
          console.log('percent --------->', percent)
          that.progress = `${percent}%`
        }
      }
      axios.post(this.url, data, config)
        .then(res => {
          const result = res.data.data

          Toast('文件上传成功！')
          setTimeout(() => {
            this.onSuccess(result)
          }, 500)
        })
        .catch(err => {
          Toast.fail({ message: '文件上传失败！' })

          setTimeout(() => {
            this.onFailed()
          }, 500)
        })
    },

    onSuccess(result) {
      uni.postMessage({
        data: {
          status: 'success',
          result
        }
      })

      uni.redirectTo({
        url: this.backUrl
      })
    },

    onFailed() {
      this.$refs.upload.value = ''
      this.progress = '0%'
      uni.postMessage({
        data: {
          status: 'failed'
        }
      })

      uni.redirectTo({
        url: this.backUrl
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.file-upload {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  padding: 20px;

  &__title {
    font-size: 30px;
    font-weight: bold;
    text-align: center;
    margin: 0 0 20px 0;
  }

  &__tips {
    margin-top: 10px;
  }

  &__button {
    display: flex;
    justify-content: center;
    margin: 20px 0;

    .upload-btn {
      padding: 8px 12px;
      width: 100%;
      border-radius: 26px;
      outline: none;
      border: none;
      font-weight: 600;
      color: #3060fd;
      font-size: 16px;
    }
  }

  .upload-container {
    height: 30vh;
    border: 2px dashed #409EFF;
    border-radius: 10px;
    &__icon {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .icon {
        font-size: 100px;
        color: #409EFF;
      }
    }
  }

  .progress-bar-container {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    flex-direction: row-reverse;
    margin-top: 10px;
    padding-left: 25px;
    .progress {
      font-size: 14px;
      color: #000000d9;
      padding-left: 4px;
      text-align: center;
    }
    .progress-bar {
      overflow: hidden;
      height: 10px;
      background-color: #f5f5f5;
      border-radius: 5px;
      flex: 1;
      .bar {
        height: 100%;
        background-color: #409EFF;
        transition: width 0.5s;
      }
    }
  }

}
</style>
